//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 刘蒙 on 16/1/12.
//  Copyright © 2016年 liumeng. All rights reserved.
//

import UIKit



class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        //webView有2个代理方法
        webView.delegate = self
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNavBar()
        
        loadOAuthPath()
    }

    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充账号
    @objc private func defaultAccount() {
        
        let jsString = "document.getElementById('userId').value = 'liumengzb11@sina.com', document.getElementById('passwd').value = 'mengloveyan520'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    
    //设置导航的关闭按钮
    private func setupNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        
    }
    
    //第三方软件请求授权请求->第三方软件获取的授权准许->
    //MARK: - 加载授权页面
    private func loadOAuthPath() {
        //这里需要拼接一个urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + "214771789" + "&redirect_uri=" + "http://www.itcast.cn"
        //这里代表,程序员承诺这里一定不为空的,
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        print(view)
        webView.loadRequest(request)
    }
    
}

//MARK: - 实现代理方法 2 + 1 + 1
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
      SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//        print("========")
//        print(request.URL?.absoluteString)
//        print("========")
        /*
        guard + Bool的表达式 else {}   一般都是这种的格式,guard后面一般都会跟随一个else语句,如果前面的判断为true的时候,跳过,如果为false的时候,就执行else里面的语句
        */
       
        //这里的目的是获取code,但是不让其进行跳转.只需要获取code就可以了
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.containsString("code=") {
            
            //将url中的参数获取到
            guard let query = request.URL?.query else {
                return false
            }
            
            let codeString = "code="
            //将query 转换NSString 
            let code = (query as NSString).substringFromIndex(codeString.characters.count)
         
            loadAccessToken(code)
            
            return false
        }
        
        //return一个true的时候,表示的就是控件可以正常使用,(如果这里使用false的话,就不会弹出微博登录的页面)
        return true
    
    }
    

    
    
    //获取token
    func loadAccessToken(code: String) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]//字典
        //利用afn进行网络请求
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result)
            
            guard let dict = result as? [String : AnyObject] else {
                print("数据格式不合法")
                return
            }
            
            //获取值
            let access_token = dict["access_token"] as! String
            let uid = dict["uid"] as! String
            
            //获取完用户的数据之后,加载用户的信息
            self.loadUserInfo(access_token, uid: uid)
            
            }) { (_, error) -> Void in
                print(error)
        }
  
    }
    
    
    
    //获取用户信息
    private func loadUserInfo(access_token: String, uid: String) {
        //获取用户信息的url
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": access_token, "uid": uid]
        
        //创建AFN
        let AFN = AFHTTPSessionManager()
      
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result)
            
            
            }) { (_, error) -> Void in
               
                print(error)
        }
        
    }
    
 
}






